package com.frxuexi.base.http

import androidx.lifecycle.MutableLiveData
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener

object WebSocketClient {
    var webSocket:WebSocket?=null
    var data=MutableLiveData<String>()

    fun start(){
        val request = Request.Builder().url("ws://10.161.9.80:7015/api/websocket/100").build()
        webSocket=OkHttpClient().newWebSocket(request,object :WebSocketListener(){
            override fun onMessage(webSocket: WebSocket, text: String) {
                data.postValue(text)
            }
        })
    }

    fun sendMessage(text:String){
        webSocket?.send(text)
    }

    fun closeSocket(){
        webSocket?.close(1000,"关闭WebSocket")
        webSocket=null
    }
}